<template>
  <div class="recommend-manager">
    <div class="manager-header">
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">
        新增品牌推荐
      </el-button>
      <el-button @click="refreshList" icon="el-icon-refresh">
        刷新
      </el-button>
    </div>

    <div class="recommend-grid">
      <div 
        v-for="brand in recommendList" 
        :key="brand.id"
        class="brand-card"
        :class="{ 'selected': selectedBrands.includes(brand.id) }"
        @click="toggleSelect(brand)"
      >
        <div class="brand-logo">
          <image-preview :src="brand.logo" :width="80" :height="80"/>
          <div class="brand-overlay">
            <el-button 
              type="primary" 
              size="mini" 
              icon="el-icon-edit"
              @click.stop="handleEdit(brand)"
            >
              编辑
            </el-button>
          </div>
        </div>
        <div class="brand-info">
          <h4>{{ brand.name }}</h4>
          <p>{{ brand.link }}</p>
          <div class="brand-status">
            <el-tag :type="brand.status === 1 ? 'success' : 'info'">
              {{ brand.status === 1 ? '已上架' : '已下架' }}
            </el-tag>
          </div>
        </div>
        <div class="select-indicator">
          <i class="el-icon-check" v-if="selectedBrands.includes(brand.id)"></i>
        </div>
      </div>
    </div>

    <div class="manager-footer">
      <div class="selected-info">
        已选择 {{ selectedBrands.length }} 个品牌推荐
      </div>
      <div class="actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确认选择
        </el-button>
      </div>
    </div>

    <!-- 品牌推荐编辑弹窗 -->
    <el-dialog 
      :title="editMode === 'add' ? '新增品牌推荐' : '编辑品牌推荐'" 
      :visible.sync="editDialogVisible"
      width="600px"
    >
      <el-form 
        ref="brandForm" 
        :model="brandForm" 
        :rules="brandRules" 
        label-width="100px"
      >
        <el-form-item label="品牌Logo" prop="logo">
          <image-upload v-model="brandForm.logo" />
        </el-form-item>
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="brandForm.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="brandForm.link" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="所属校区" prop="campusId" v-if="isAdmin">
          <el-select v-model="brandForm.campusId" placeholder="请选择校区" style="width: 100%">
            <el-option
              v-for="campus in campusList"
              :key="campus.campusId || campus.id"
              :label="campus.campusName || campus.name"
              :value="campus.campusId || campus.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属校区" v-else>
          <el-input :value="getCurrentCampusName()" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="brandForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecommendations, getRecommendations, addRecommendations, updateRecommendations } from '@/api/home/recommendations/recommendations'

export default {
  name: 'RecommendManager',
  props: {
    selected: {
      type: Array,
      default: () => []
    },
    currentCampusId: {
      type: Number,
      default: null
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    campusList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      recommendList: [],
      selectedBrands: [],
      editDialogVisible: false,
      editMode: 'add',
      brandForm: {
        id: null,
        logo: '',
        name: '',
        link: '',
        status: 1,
        campusId: null
      },
      brandRules: {
        logo: [
          { required: true, message: '请上传品牌Logo', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        link: [
          { required: true, message: '请输入跳转链接', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadRecommendList()
    this.initializeSelected()
  },
  watch: {
    selected: {
      handler() {
        this.initializeSelected()
      },
      immediate: true
    }
  },
  methods: {
    // 初始化已选择项
    initializeSelected() {
      if (this.selected && this.selected.length > 0) {
        this.selectedBrands = this.selected.map(item => 
          typeof item === 'object' ? item.id : item
        )
      } else {
        this.selectedBrands = []
      }
    },

    // 加载品牌推荐列表
    async loadRecommendList() {
      try {
        const query = { status: 1 } // 只显示已上架的
        
        // 如果不是超级管理员，添加校区筛选
        if (!this.isAdmin && this.currentCampusId) {
          query.campusId = this.currentCampusId
        }
        
        const response = await listRecommendations(query)
        this.recommendList = response.rows || []
      } catch (error) {
        this.$message.error('加载品牌推荐列表失败')
      }
    },

    // 切换选择状态
    toggleSelect(brand) {
      const index = this.selectedBrands.indexOf(brand.id)
      if (index > -1) {
        this.selectedBrands.splice(index, 1)
      } else {
        this.selectedBrands.push(brand.id)
      }
    },

    // 新增品牌推荐
    handleAdd() {
      this.editMode = 'add'
      this.resetForm()
      this.editDialogVisible = true
    },

    // 编辑品牌推荐
    handleEdit(brand) {
      this.editMode = 'edit'
      this.brandForm = { ...brand }
      this.editDialogVisible = true
    },

    // 保存品牌推荐
    async handleSave() {
      this.$refs.brandForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.editMode === 'add') {
              await addRecommendations(this.brandForm)
              this.$message.success('新增成功')
            } else {
              await updateRecommendations(this.brandForm)
              this.$message.success('更新成功')
            }
            
            this.editDialogVisible = false
            this.loadRecommendList()
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.brandForm = {
        id: null,
        logo: '',
        name: '',
        link: '',
        status: 1,
        campusId: this.isAdmin ? null : this.currentCampusId
      }
    },

    // 获取当前校区名称
    getCurrentCampusName() {
      if (!this.currentCampusId) {
        return '超级管理员'
      }
      const campus = this.campusList.find(c => 
        (c.campusId || c.id) === this.currentCampusId
      )
      return campus ? (campus.campusName || campus.name) : '未知校区'
    },

    // 刷新列表
    refreshList() {
      this.loadRecommendList()
    },

    // 取消选择
    handleCancel() {
      this.$emit('close')
    },

    // 确认选择
    handleConfirm() {
      const selectedBrandData = this.recommendList.filter(brand => 
        this.selectedBrands.includes(brand.id)
      )
      this.$emit('select', selectedBrandData)
    }
  }
}
</script>

<style scoped>
.recommend-manager {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.recommend-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  overflow-y: auto;
  padding: 10px 0;
}

.brand-card {
  position: relative;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.brand-card:hover {
  border-color: #1976d2;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15);
}

.brand-card.selected {
  border-color: #1976d2;
  background-color: #e3f2fd;
}

.brand-logo {
  position: relative;
  height: 120px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.brand-logo >>> .el-image {
  max-width: 80%;
  max-height: 80%;
}

.brand-logo >>> .el-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.brand-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.brand-card:hover .brand-overlay {
  opacity: 1;
}

.brand-info {
  padding: 15px;
}

.brand-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.brand-info p {
  margin: 0 0 10px 0;
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.brand-status {
  display: flex;
  justify-content: flex-end;
}

.select-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #1976d2;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.brand-card.selected .select-indicator {
  opacity: 1;
}

.manager-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 10px;
}
</style> 